# Copyright (c) 2020 Presto Labs Pte. Ltd.
# Author: donggu

import re
import time
import toml
import enum

class SourceEnum(enum.IntEnum):
  EXCHANGE = 1
  DUMMY = 2

def embed_source(ts, source):
  return (ts // 10) * 10 + source

class ProductInfoDefault(object):
  def __init__(self):
    with open('data/coin2/product_info/default.toml') as f:
      self.default = toml.load(f)

    with open('data/coin2/order/fee_info.toml') as f:
      self.fee = toml.load(f)

    self.fetched_time = embed_source(time.time_ns(), SourceEnum.EXCHANGE)
    # self.source = "EXCHANGE"

  def product_info(self, me, norm_symbol):
    assert me.count('.') == 1  # Spot.Okex, not Spot.Okex.v3

    if isinstance(self.default[me], list):  # multiple regex rules
      info = {}
      for rule in self.default[me]:
        if ('regex' not in rule) or re.search(rule['regex'],
                                              norm_symbol):  # last matching rule applies

          info = {**info, **rule}
    else:
      info = self.default[me]

    if me in self.fee:
      if isinstance(self.fee[me], list):  # multiple regex rules
        for rule in self.fee[me]:
          if ('regex' not in rule) or re.search(rule['regex'], norm_symbol):
            info = {**info, **rule}
            break
      else:
        info = {**info, **self.fee[me]}

    assert 'maker_fee' in info, f'maker_fee should be provided by hand, for safety! me={me} norm={norm_symbol}, info={info}'  # noqa:E501
    assert 'taker_fee' in info, f'taker_fee should be provided by hand, for safety! me={me} norm={norm_symbol}, info={info}'  # noqa:E501

    info["fetched_time"] = self.fetched_time
    # info["source"] = self.source

    return info
